package com.angel.data.generator.interfaces.impl;

import java.io.InputStream;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;

import com.angel.dao.generic.factory.DAOFactory;
import com.angel.data.generator.exceptions.DataGeneratorException;
import com.angel.data.generator.interfaces.DataGenerator;
import com.angel.io.exceptions.InvalidRowDataException;
import com.angel.io.processors.runners.imports.ImportProcessorRunner;

/**
 *
 * @author William
 *
 */
public abstract class ImportFileDataGenerator implements DataGenerator{

	private static final long serialVersionUID = 7116397445717602280L;

	private static final Logger LOGGER = Logger.getLogger(ImportFileDataGenerator.class);
	private Integer[] pages;

	public abstract ImportProcessorRunner prepareImportFileProcessorRunner();

	public abstract InputStream prepareInputStream();

	public ImportFileDataGenerator(){
		super();
	}

	public ImportFileDataGenerator(Integer ... pages){
		super();
		this.pages = pages;
	}

	public void generateData(Collection<Object> dataCollection, DAOFactory daoFactory) {
		try {
			LOGGER.info("Preparing input stream.");
			InputStream inputStream = this.prepareInputStream();
			LOGGER.info("Preparing import file processor runner.");
			ImportProcessorRunner importFileProcessorRunner = this.prepareImportFileProcessorRunner();
			LOGGER.info("Begin run process for [" + this.getStringPages() + "] pages.");
			List<Object> entities = importFileProcessorRunner.runProcess(inputStream, this.getPages());
			LOGGER.info("End run process. It process [" + entities.size() + "] entities.");
			dataCollection.addAll(entities);
		} catch (InvalidRowDataException e) {
			throw new DataGeneratorException("An unexpected error ocurred running import process.", e);
		} catch (Exception e) {
			throw new DataGeneratorException("An unexpected error ocurred running import process.", e);
		}
	}

	protected String getStringPages() {
		String pages = "";
		if(this.getPages() != null){
			for(Integer page: this.getPages()){
				if(page.equals(this.getPages()[this.getPages().length - 1])){
					pages = pages.concat(page.toString());
				} else {
					pages = pages.concat(page.toString() + ", ");
				}

			}
		} else {
			pages = "0";
		}
		return pages;
	}

	/**
	 * @return the pages
	 */
	public Integer[] getPages() {
		return pages;
	}

	/**
	 * @param pages the pages to set
	 */
	public void setPages(Integer[] pages) {
		this.pages = pages;
	}
}
